package com.bruce.asurada.util;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;

import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

/**
 * HTTP请求工具类，替代Feign调用SSO-Server
 */
@Component
@Slf4j
public class HttpClientUtil {

    @Resource
    private RestTemplate restTemplate;

    /**
     * 发送GET请求
     * @param <T>
     * @param url 请求地址
     * @param params 请求参数
     * @param responseType 返回值类型
     * @return
     * @throws Exception
     */
    public <T> T get(String url,Map<String, Object> params, ParameterizedTypeReference<T> responseType) throws Exception{
       ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(params), responseType);
       return response.getBody();
    }


    /**
     * 发送GET请求
     * @param <T>
     * @param url 请求地址
     * @param headrers 请求参数
     * @param responseType 返回值类型
     * @return
     * @throws Exception
     */
    public <T> T get(String url,HttpHeaders headers, ParameterizedTypeReference<T> responseType) throws Exception{
       ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.GET, new HttpEntity<>(headers), responseType);
       return response.getBody();
    }


    /**
     * 发送POST的HTTP请求
     * @param <T>
     * @param url 请求地址
     * @param params 请求参数
     * @param responseType 返回值类型
     * @return
     * @throws Exception
     */
    public <T> T post(String url, Map<String, String> params, ParameterizedTypeReference<T> responseType) throws Exception{
       HttpHeaders headers = new HttpHeaders();
       headers.setContentType(MediaType.APPLICATION_JSON); 
       HttpEntity<Map<String, String>> request = new HttpEntity<>(params, headers);
       ResponseEntity<T> response = restTemplate.exchange(url, HttpMethod.POST, request, responseType);
       return response.getBody();
    }
}
